/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.sharedbills.client.stores;

import java.util.ArrayList;

import org.jb.sharedbills.client.gin.EventId;
import org.jb.sharedbills.shared.dto.Message;
import org.jb.sharedbills.shared.svc.MessageServiceAsync;

import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.LoadListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class MessageStore extends ListStore<BeanModel> {

	@SuppressWarnings("unchecked")
	@Inject
	public MessageStore( @EventId final String eventId,
						 final MessageServiceAsync messageService) {

		RpcProxy<ArrayList<Message>> proxy = new RpcProxy<ArrayList<Message>>() {  
			@Override  
			protected void load(Object loadConfig, AsyncCallback<ArrayList<Message>> callback) {  				
				messageService.getMessages(eventId, callback);
			}  
		};  
		  
		this.loader = (BaseListLoader)new BaseListLoader<ListLoadResult<Message>>(  proxy, new BeanModelReader());
		loader.addLoadListener(new LoadListener() {

		      public void loaderBeforeLoad(LoadEvent le) {
		        onBeforeLoad(le);
		      }

		      public void loaderLoad(LoadEvent le) {
		        onLoad(le);
		      }

		      public void loaderLoadException(LoadEvent le) {
		        onLoadException(le);
		      }

		    });
		
		loader.load();
	}
	
	/**
	 * 
	 * @param message
	 */
	public void addNewMessage( Message message ) {
		BeanModel model = messageFactory.createModel(message);
		
		insert( model, 0 );
	}
	
	private static BeanModelFactory messageFactory = BeanModelLookup.get().getFactory(Message.class);
}
